﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Drawing;


namespace MobileOSMLib
{
    public class OSMTilesProvider : ITilesProvider
    {
        private HttpWebRequest httpRequest;

        public OSMTilesProvider()
        {
        }
        public double calculateLat(double tx, double ty, int zoom)
        {
            return 0; // TODO implement
        }

        public double calculateLon(double tx, double ty, int zoom)
        {
            return 0; // TODO implement
        }

        public double calculateTileX(double lon, double lat, int zoom)
        {

            return ((lon + 180) / 360) * Math.Pow(zoom, 2);
        }

        public double calculateTileY(double lon, double lat, int zoom)
        {
            double resultY;
            lat *= Math.PI / 180.0;
            resultY = (1 - (Math.Log10(Math.Tan(lat) + 1 / Math.Cos(lat)) / Math.PI)) / 2 * Math.Pow(zoom, 2);
            return resultY;
        }

        public int getMaxZoom()
        {
            return 18;
        }

        public Bitmap requestTile(int tx, int ty, int zoom)
        {
            Bitmap tileOSM = null;
            try
            {
                Uri uri = new Uri("http://tile.openstreetmap.org/" + zoom + "/" + tx + "/" + ty + ".png");
                httpRequest = (HttpWebRequest)HttpWebRequest.Create(uri);

                HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse();
                Stream imageStream = httpResponse.GetResponseStream();
                tileOSM = new Bitmap(imageStream);
                httpResponse.Close();
                imageStream.Close();

            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex);
            }
            return tileOSM;
        }

        private bool checkParamsGeo(double lon, double lat, int zoom)
        {
            bool isGeoOK;
            isGeoOK = (lon >= -180) && (lon <= 180) && (lat >= -85.0511) && (lat <= 85.0511) && (zoom >= 0) && (zoom <= 18);
            return isGeoOK;

        }

        private bool checkParamsTiles(double tx, double ty, int zoom)
        {
            bool isTilesOK;
            int powzoom;
            powzoom = (int)Math.Pow(zoom, 2) - 1;
            isTilesOK = (zoom >= 0) && (zoom <= 18) && (tx >= 0) && (tx <= powzoom) && (ty >= 0) && (ty <= powzoom);
            return isTilesOK;
        }


    }
}
